import { useStore, mapState, mapGetters, createNamespacedHelpers } from 'vuex'
import { computed } from 'vue'

type Fn = (mapp?: any) => any

function useMapper(mapper: any, fnc: Fn) {
  // 拿到store独享
  const store = useStore()
  // 获取到对应的对象的functions: {name: function, age: function}
  const storeStateFns = fnc(mapper)
  const storeState: any = {}
  // 对数据进行转换
  Object.keys(storeStateFns).forEach((fnKey) => {
    //这里绑定this的原因是computed计算属性在进行查找的时候默认会采用this.$store
    //由于setup中没有this绑定(this是undefined)，所以我们需要调用bind手动进行绑定
    const fn = storeStateFns[fnKey].bind({ $store: store })
    storeState[fnKey] = computed(fn)
  })
  return storeState
}

//MapState
export function useMapState(moduleName: any, mapper: any) {
  let mapperFn = mapState
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapState
  } else {
    mapper = moduleName
  }

  return useMapper(mapper, mapperFn)
}

//MapGetters
export function useMapGetters(moduleName: any, mapper: any) {
  let mapperFn = mapGetters
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapGetters
  } else {
    mapper = moduleName
  }

  return useMapper(mapper, mapperFn)
}
